<template>
	<cmDialog v-model="visible" modal-title="菜单权限分配" model-width="600px">
		<!-- <div style="padding: 20px 40px;"> -->
		<div class="form-label">已选择的权限：</div>
		<el-tag v-for="tag in state.tags" :key="tag.name" class="mx-1 mx-tag" closable @close="handleClose(tag)">
			{{ tag.name }}
		</el-tag>
		<div class="tree-content">
			<el-tree
				ref="treeTemplate"
				show-checkbox
				:data="menuList"
				node-key="id"
				:default-expand-all="true"
				check-strictly
				:render-after-expand="false"
				style="width: 100%"
				clearable
				@check-change="handleCheckChange"
			/>
		</div>
		<div class="dialog-foot">
			<el-button type="primary" @click="handleAddFormSubmit">保存</el-button>
		</div>
		<!-- </div> -->
	</cmDialog>
</template>
<script lang="ts" setup>
import cmDialog from '@/components/cm-dialog/index.vue'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElTree } from 'element-plus'

import { useUserInfoApi } from '@/api/sys/user'
import { template } from 'xe-utils'

const visible = ref(false)
const menuList = ref([])
const treeTemplate = ref<InstanceType<typeof ElTree>>()

// const tags = ref([])
const state = reactive({
	tags: []
})

// 监听整个对象的变化
watch(
	() => state.tags,
	(newValue, oldValue) => {
		// 更新画面
	},
	{ deep: true }
)

const init = (isUpdate: boolean, row: any) => {
	visible.value = true

	if (isUpdate) {
		// isUpdate  true-新增  、false-编辑row有数据 反显
		// 重置画面数据
		tags.value = []
	}

	// 菜单列表
	getMenuList()
}
// 获取菜单列表
const getMenuList = async () => {
	const { data } = await useUserInfoApi() // 获取用户信息
	// console.log(data)
	menuList.value = data.menuList
}

// 点击树节点事件处理
const handleCheckChange = (data: Object) => {
	// console.log(state.tags, data)
	const newArr = state.tags
	let index = newArr.findIndex(item => item.name === data.label)
	// console.log(index)
	if (index !== -1) {
		newArr.splice(index, 1)
	} else {
		newArr.push({ name: data.label, id: data.id, label: data.label })
	}
}

const handleClose = (tag: string) => {
	state.tags.splice(state.tags.indexOf(tag.name), 1)
}

// 更新角色
const handleAddFormSubmit = async () => {}

defineExpose({
	init
})
</script>
<style scoped>
.dialog-foot {
    text-align: center;
}

.tree-content {
    margin-top: 20px;
}

.form-label {
    padding-bottom: 5px;
}

.mx-tag {
    margin-left: 5px;
    margin-right: 5px;
    margin-bottom: 5px;
}
</style>
